buttonW=80

//设置倒数第一行字体默认大小,最后一行为空行，他会随着倒数第二行大小变化
fontS=5
uploadPercent=0
imgFile=""
//通过计数图片实现修改时第一次进入这个页面就不用保存
CImg=0
tempCimg=0
//判断是否第一次进入编辑页面
firstEnter="yes"
//如果在编辑框拖拉文件就不上传
textAreaDragFlage="no"
//检验是否保存：解决上传之后的保存
noCheckSave="no"
//修改或导入
changFlag="no"
//保存原始的类
oldCls=""
//保存原始的名称
oldTitle=""
//文件路径
filePath="../../datas/file/"
//表格变红色的索引
indexList=[]
//判断是否是手机
phone=false
window.onload=function()
{
phone=isMobile()
//判断是否是修改还是添加
loadData()
showUI()
//撤销
undo()
//前进
redo()
//格式刷
//加粗
bold()
//斜体
italic()
//下划线
underline()
// 贯穿线
strikeThrough()
//文字颜色
foreColor()
//背景颜色
backgroundColor()
//字号
fontSize()
//行距
lineHeight()
//字距
foneWidth()
//左对齐
justifyLeft()
//居中对齐
justifyCenter()
//右对齐
justifyRight()
//端对齐
justifyFull()
//插入图片
insertImg()

//插入表格
insertTable()
//格式刷
cpFormat()
//显示代码
toHtml()
//进行页面监听确保页面里有空白的<p><br></p>
setP()
//点击保存
save()
//键盘监听
listenKey()
//编辑框文件拖拉显示
editeUpLoadFile()
//判断登录
pandLogin()
//颜色盘
colorPlane()


}








// 命令执行函数
function execute(command,value=null,bloone=false)
{
 document.execCommand(command,bloone,value)
}


var  historyStack={}

//获取元素的样式
function getCss(ele,id)
{
 var tableBox=ele

 var childs=tableBox.children 
 var c=0
 var p=""
 for(var i=0;i<childs.length;i++)
 {

  if(childs[i].className!=undefined&&childs[i].className!=null&&childs[i].className.length!=0)
  {
   historyStack[id][childs[i].className]=childs[i].style.width+";"+childs[i].style.height+";"
  }
  else
  {

   p=childs[i].parentNode
   while(p.className.length==0)
   {
    p=p.parentNode
   }
   historyStack[id][p.className+"#"+childs[i].tagName+"#"+c]=childs[i].style.width+";"+childs[i].style.height
   c+=1
  }
  getCss(childs[i],id)
  
 }
}

//撤销
function undo()
{
 var ele=document.getElementById('undo')
 ele.onclick=function()
 {  
  execute("undo")
  //在输入监控中已经有了
  //解决返回到张贴的表格时出现没有修饰的问题 
  // setTimeout(function()
  //  {
  //     initTalbe()
  //  },100)
 }
 
 
}

//前进
function redo()
{
 var ele=document.getElementById('redo')
 tabText=document.getElementById("textArea")
 ele.onclick=function()
 {  
  execute("redo")
  
  //在输入监控中已经有了
  //解决返回到张贴的表格时出现没有修饰的问题
  // setTimeout(function()
  //  {
  //     initTalbe()
  //  },100)
 }
}





//加粗
function bold()
{
 var ele=document.getElementById('bold')
 ele.onclick=function()
 {
  execute("bold")
 }
}


//斜体
function italic()
{
 var ele=document.getElementById('italic')
 ele.onclick=function()
 {
  execute("italic")
 }
}


//下划线
function underline()
{
 var ele=document.getElementById('underline')
 ele.onclick=function()
 {
  execute("underline")
 }
}

// 贯穿线
function strikeThrough()
{
 var ele=document.getElementById("strikeThrough")
 ele.onclick=function()
 {
  execute("strikeThrough")
 }
}
//文字颜色
function foreColor()
{
 var ele=document.getElementById('fonteColor1')
 var fonteColorBox=document.getElementById('fonteColorBox')
 var getColor1=document.getElementById("getColor1")
 var showColor1=document.getElementById("showColor1")

 showColor1.onclick=function()
 {
  if(!getStyle(fonteColorBox,3))
  {
   fonteColorBox.style.display="block"
   fonteColorBoxToCenter()
   getColor1.focus()
   closeOtherAlter("fonteColorBox")
   moveBox(fonteColorBox)
  }
  else
  {
   fonteColorBox.style.display="none"
  }
 }

 getColor1.onblur=function()
 {
  fonteColorBox.style.display="none"
 }

    getColor1.addEventListener("input",function()
    {
     showColor1.style.background=getColor1.value
    })
 ele.onclick=function()
 {
  execute("foreColor",getColor1.value)
  fonteColorBox.style.display="none"
 }
 ele.addEventListener("touchstart",function()
 {
   var getColor1=document.getElementById("getColor1")
   execute("foreColor",getColor1.value)
   fonteColorBox.style.display="none"
 })
}

//背景颜色
function backgroundColor()
{
 var ele=document.getElementById('backgroundColor')
 var backgroundColorBox=document.getElementById('backgroundColorBox')
 var getColor2=document.getElementById("getColor2")
    var showColor2=document.getElementById("showColor2")

 showColor2.onclick=function()
 {
      
  if(!getStyle(backgroundColorBox,3))
  {
   backgroundColorBox.style.display="block"
   backgroundColorBoxToCenter()
   getColor2.focus()
   closeOtherAlter("backgroundColorBox")
   moveBox(backgroundColorBox)

  }
  else
  {
   backgroundColorBox.style.display="none"
   
  }
 }
 getColor2.onblur=function()
 {
  backgroundColorBox.style.display="none"
 }
 
 getColor2.addEventListener("input",function()
    {
     showColor2.style.background=getColor2.value
    })


 ele.onclick=function()
 {
  execute("backColor",getColor2.value)
  showColor2.style.background=getColor2.value
  backgroundColorBox.style.display="none"
 }
 ele.addEventListener("touchstart",function(){
   var getColor2=document.getElementById("getColor2")
   execute("backColor",getColor2.value)
   backgroundColorBox.style.display="none"
 })

}




//字号
function fontSize()
{
 var textArea=document.getElementById("textArea")
 var ele=document.getElementById('fontSize')
 var fontSizeBox=document.getElementById('fontSizeBox')
 var button=document.getElementById("fontSizeYese")
 var getValue=document.getElementById("fontSizeValue")

 

 ele.onclick=function()
 {
      
  if(!getStyle(fontSizeBox,3))
  {
   fontSizeBox.style.display="block"
   fontSizeToCenter()
   moveBox(fontSizeBox)
   closeOtherAlter("fontSizeBox")
  }
  else
  {
   fontSizeBox.style.display="none"
   
  }
  
 }
  
 var active="click"
 if(phone)
 {
   active="touchstart"
 }
 
  button.addEventListener(active,function()
  {
      execute("fontSize","5")
     
     //下面的函数是让最后的两个p保持一样的字号，这里不需要
      // var p=textArea.getElementsByTagName("p")
      // var length=p.length
      // if(length>=2)
      // {
      //  var p2=p[length-2].getElementsByTagName("font")
      //  if(p2!=undefined)
      //  {
      //   var lastP=p[length-1].getElementsByTagName("font")
      //   if(lastP!=undefined)
      //   {
      //    fontS=p2[p2.length-1].getAttribute("size")
      //    lastP[lastP.length-1].setAttribute("size",fontS)
      //   }
      //  }
      // }

   var font=document.getElementsByTagName("font")
   for(var i=0;i<font.length;i++)
   {
      if(font[i].size==5)
      {  
         var value=parseInt(getValue.value)
         if(isNaN(value))
         {
            alert("请输入纯数字")
            return
         }
         else
         {
            font[i].style.fontSize=value
            font[i].setAttribute("size","1")
         }
      }
   }
   fontSizeBox.style.display="none"
 })
}



//行距
function lineHeight()
{
   var lineH=document.getElementById("lineHeight")
   var lineHBox=document.getElementById("lineHeightBox")
   var lineHeightValue=document.getElementsByClassName("lineHeightValue")
   var lineHeightYes=document.getElementById("lineHeightYes")
   var editeArea=document.getElementById("textArea")
   var action="click"

   if(!phone)
   {
      action="click"
   }
   else
   {
      action="touchstart"
   }



   lineH.addEventListener(action,function(e)
   {
     closeOtherAlter("lineHeightBox")
     
     var  show=lineHBox.style.display
     if(show==""||show=="none")
     {
        lineHBox.style.display="block"
        moveBox(lineHBox)
     }
     else
     {
       lineHBox.style.display="none"
     }
   })
   for(var i=0;i<lineHeightValue.length;i++)
   {
      lineHeightValue[i].addEventListener(action,function(e)
      {
         var value=this.innerText.replace(/\s+/ig,"")
         var sc=document.getSelection()
         var parent=sc.anchorNode.parentNode
         
         if(parent.contains(editeArea)||parent==editeArea)
         {
            alert("所选的不是编辑框中内容，请重选")
            return
         }
         else
         {
            $().selsectObj({"style":"lineHeight:"+value},"textArea",sc)
            lineHBox.style.display="none"
         }
        
      })
   }
}

//字距
function foneWidth()
{
   var foneW=document.getElementById("foneWidth")
   var foneWBox=document.getElementById("foneWidthBox")
   var foneWidthValue=document.getElementsByClassName("foneWidthValue")
   var foneWidthYes=document.getElementById("foneWidthYes")
   var editeArea=document.getElementById("textArea")
   var action="click"
   if(!phone)
   {
      action="click"
   }
   else
   {
     action="touchstart"
   }
   foneW.addEventListener(action,function(e)
   {
      closeOtherAlter("foneWidthBox")
      var  show=foneWBox.style.display
      
      if(show==""||show=="none")
      {
         foneWBox.style.display="block"
         moveBox(foneWBox)
      }
      else
      {
         foneWBox.style.display="none"
      }
   })


   for(var i=0;i<foneWidthValue.length;i++)
   {
      foneWidthValue[i].addEventListener(action,function(e)
      {
         var value=this.innerText.replace(/\s+/ig,"")
         var sc=document.getSelection()
          var parent=sc.anchorNode.parentNode
         
         if(parent.contains(editeArea)||parent==editeArea)
         {
            alert("所选的不是编辑框中内容，请重选")
            return
         }
         else
         {
            $().selsectObj({"style":"letterSpacing:"+value},"textArea",sc)
            foneWBox.style.display="none"
         }
         
      })
   }



}
let savedSelection = null;
function saveSelection() {
  const selection = window.getSelection();
  if (selection.rangeCount > 0) {
    savedSelection = selection.getRangeAt(0).cloneRange();
  }
}
function setLineHeight(height) {
      const selection = window.getSelection();
      if (!selection.rangeCount) return;
      
      const span = document.createElement('span');
      span.dataset.lineHeight = height;
      span.style.lineHeight = height;
      
      const range = selection.getRangeAt(0).cloneRange();
      range.surroundContents(span);
    }
function restoreSelection() {
  if (savedSelection) {
    const selection = window.getSelection();
    selection.removeAllRanges();
    selection.addRange(savedSelection);
  }
}

//左对齐
function justifyLeft()
{
 var ele=document.getElementById('justifyLeft')
 ele.onclick=function()
 {
  execute("justifyLeft")
 }
}

//居中对齐
function justifyCenter()
{
 var ele=document.getElementById('justifyCenter')
 ele.onclick=function()
 {
  execute("justifyCenter")
 }
}
//右对齐
function justifyRight()
{
 var ele=document.getElementById('justifyRight')
 ele.onclick=function()
 {
  execute("justifyRight")
 }
}



//端对齐
function justifyFull()
{
 var ele=document.getElementById('justifyFull')
 ele.onclick=function()
 {
  execute("justifyFull")
 }
}



let formatCommand=[]

//格式刷
function cpFormat()
{

 let flag=false
 var ele=document.getElementById('cpFormat')
 //获取格式，并打开鼠标再次框选就张贴格式的监听
 ele.onclick=function()
 {
  const commands=["bold","italic","underline",
  "strikeThrough","fontSize","foreColor",
  "backColor","justifyFull","justifLeft",
  "justifyRgiht"]
  if(flag==false)
  {
   flag=true
   commands.forEach(command=>
   {
    const state=document.queryCommandState(command)
    const value=document.queryCommandValue(command)
    formatCommand.push({command,state,value})
   })
   document.addEventListener("mouseup",postFormat)
  }
 }

 //张贴函数，并移除鼠标监听
 function postFormat()
 {
  flag=false
  formatCommand.forEach(({command,state,value})=>
  {
   if(value!='false'&&value.length!=0)
   {
    execute(command,value)
   }
   else if(state==true)
   {
    execute(command)
   }
  })
  document.removeEventListener('mouseup', postFormat);
 }
}

//修改表格的函数


//插入表格
function insertTable()
{
 var ele=document.getElementById("insertTable")
 var insertTableBox=document.getElementById("insertTableBox")
 var yes=document.getElementById("insertTableYes")
 var cancel=document.getElementById("insertTableCancel")
 var textArea=document.getElementById("textArea")
 
 ele.onclick=function()
 {
  if(!getStyle(insertTableBox,3))
  {
   insertTableBox.style.display="block"
   tableInsertToCenter()
   moveBox(insertTableBox)
   closeOtherAlter("insertTableBox")
    insertTableBox.style.top=20+"px"
  }
  else
  {
   insertTableBox.style.display="none"
  }
 }
 
  
  

 cancel.onclick=function(evnet)
 {
  var evnet=evnet||window.evnet
     evnet.stopPropagation();
     insertTableBox.style.display="none"


 }
  
 yes.onclick=function(evnet)
 {
  var evnet=evnet||window.evnet
     evnet.stopPropagation();
     var ip=insertTableBox.getElementsByTagName("input")
     var now=new Date()
     var year = now.getFullYear();
     var month = now.getMonth() + 1
     var day = now.getDate()
     var hours = now.getHours()
     var minutes = now.getMinutes()
     var seconds = now.getSeconds()
     var time=""+year+month+day+hours+minutes+seconds
     var columLi=[]
     var rowLi=[]

     var hang=parseInt(ip[0].value)
     var lie=parseInt(ip[1].value)
 
     var tableBox=document.createElement("div")
     // var insertTableArea=document.createElement("p")
     var columBox=document.createElement("ul")
     var rowBox=document.createElement("ul")
     var newTabe=document.createElement("table")
     newTabe.id="table"+time
     var flag=false

     // columBox.setAttribute("contenteditable","false")
     // rowBox.setAttribute("contenteditable","false")
    
     tableBox.className="tableBox"
     columBox.className="columBox"
     rowBox.className="rowBox"
     // insertTableArea.className="insertTableArea"

     // insertTableArea.contenteditable="true"
     newTabe.className="table"
     //行索引
     for(var r=0;r<hang;r++)
     { 
      var tr=document.createElement("tr")
      var li=document.createElement("li")
      li.setAttribute("contenteditable","false")
      li.innerText=r+1
      //列索引
      for(var c=0;c<lie;c++)
      {
        
        if(r==0)
       {
         tr.innerHTML+="<th class='"+r+"-"+c+"' style='width:50px;height:30px;'></th>"
       }
       else
       {
        tr.innerHTML+="<td class='"+r+"-"+c+"' style='width:50px;height:30px;'></td>"
       }
       if(flag==false)
       {
        var cli=document.createElement("li")
        cli.innerText=c+1
        cli.setAttribute("contenteditable","false")
        columBox.appendChild(cli)
       }

       if(c==lie-1)
       {
        flag=true
       }
       
      }
      newTabe.appendChild(tr)
      rowBox.appendChild(li)

     }
     
     newTabe.style.float="left"
     rowBox.style.float='right'
     newTabe.style.height=hang*30+"px"
     

     // insertTableArea.appendChild(newTabe)
     
     tableBox.appendChild(columBox)
     tableBox.appendChild(newTabe)
     tableBox.appendChild(rowBox)
     var tmp=document.createElement("span")
     tmp.appendChild(tableBox)
     textArea.focus()
     execute("insertHTML",tmp.innerHTML)
     tableBox=document.getElementsByClassName("tableBox")
     
     for(var i=0;i<tableBox.length;i++)
     {
      table=tableBox[i].getElementsByTagName("table")[0]
      columBox=tableBox[i].getElementsByClassName("columBox")[0]
     
      rowBox=tableBox[i].getElementsByClassName("rowBox")[0]
      tableBox[i].style.width=(lie+1)*50+1+"px"
      tableBox[i].style.height=hang*30+30+"px"
      table.style.width=lie*50+"px"
      table.style.height=hang*30+"px"
      table.style.tableLayout="fixed"

      columBox.style.width=lie*50+"px"
      rowBox.style.height=hang*30+"px"
      columLi=columBox.getElementsByTagName("li")
      rowLi=rowBox.getElementsByTagName("li")
      editeTable(table,columLi,"colume")
      editeTable(table,rowLi,"row")
     }
     
     insertTableBox.style.display="none"
 }
}


//删除表格
function deleTable()
{  
  
   var textArea=document.getElementById("textArea")

   var  selection = document.getSelection();
   if (!selection.rangeCount)
   {
      alert("删除表格出现错误，请点击被删除表格的单元格")
      return;
   } 

  
   var  range = selection.getRangeAt(0);
   var  cp=range.commonAncestorContainer
   
   if(range.commonAncestorContainer instanceof Text)
   {
    cp=cp.parentNode
   }
   while(cp.tagName!="TABLE")
   {
      cp=cp.parentNode
      //保证不超出表格
      if(cp==null||cp.getElementsByTagName("table").length!=0)
      {
         alert("删除表格出现错误，请点击被删除表格的单元格")
         return
      }
   }
   cp=cp.parentNode
   cp.parentNode.removeChild(cp)
}


//插入图片
function insertImg()
{ 
 var flag=false
 var showImgBox=document.getElementById("showImgBox")
 var imgP=document.getElementById("showImg")
 var showImg=imgP.getElementsByTagName("img")[0]
 var video=imgP.getElementsByTagName("video")[0]
 var a=imgP.getElementsByTagName("a")[0]
 var selectFile=document.getElementById("file")
 var selectionButton=document.getElementById("selectionButton")
 var cancelButton=document.getElementById("cancelButton")
 var yesButton=document.getElementById("yesButton")
 var img=document.getElementById("insertImg")
 img.onclick=function()
 {   
  

  if(!getStyle(showImgBox,3))
  {   
   showImgBox.style.display="block"
   showImg.src="../../datas/img/showImg.jpg"
   showImg.style.display="block"
   a.style.display="none"
   video.style.display="none"
   

   imgP.addEventListener("dragstart",function(e)
   {
    e.preventDefault()
   })
   imgP.addEventListener("dragover",function(e)
   {
    e.preventDefault()
   })
   
   imgP.addEventListener("drop",function(e)
   {
    e.preventDefault()
    imgFile=e.dataTransfer.files[0]
    var reader=new FileReader()
    reader.readAsDataURL(imgFile)
    reader.onload=function(e)
    {
     if(imgFile.type.includes("image"))
     {
      showImg.src=e.target.result
      showImg.style.display="block"
      a.style.display="none"
      video.style.display="none"
     }
     else if(imgFile.type.includes("video"))
     {   
      video.src=e.target.result
      video.style.display="block"
      showImg.style.display="none"
      a.style.display="none"
     }
     else
     {
      video.style.display="none"
      showImg.style.display="none"
      a.style.display="block"
      a.href=""
      a.innerText=imgFile.name
     }

    }
    flag=true
   })

   imgToCenter()
   closeOtherAlter("showImgBox")
   moveBox(showImgBox)

  }
  else
  {
   showImgBox.style.display="none"
  }
 }

 selectionButton.onclick=function () 
 {
  selectFile.click()
  selectFile.onchange=function(e)
  {
   
   var reader=new FileReader()
   imgFile=selectFile.files[0]
   reader.readAsDataURL(imgFile)
   reader.onload=function(e)
   {  

    if(imgFile.type.includes("image"))
    {
     showImg.src=e.target.result
     showImg.style.display="block"
     a.style.display="none"
     video.style.display="none"
    }
    else if(imgFile.type.includes("video"))
    {   
     video.src=e.target.result
     video.style.display="block"
     showImg.style.display="none"
     a.style.display="none"
    }
    else
    {
     video.style.display="none"
     showImg.style.display="none"
     a.style.display="table-cell"
     a.href=""
     a.innerText=imgFile.name
    }
   }
  }
  
  flag=true
  
 }
 cancelButton.onclick=function()
 {
  showImgBox.style.display="none"
  imgFile=""
  flag=false
  showStatus("已经取消")
 }
 yesButton.onclick=function()
 {
  if(flag==true)
  {
   if(imgFile=="")
   {
    imgFile=selectFile.files[0]
   }
   flag=false
   var title=getTiltle()
   var cls=getCls()
   if(title==false)
   {
      alert("标题为空")
    return
   }
   if(cls==false)
   {
      alert("分类为空")
     return
   }
   var dic=new FormData()
   dic.append("flag","upload")
   dic.append("cls",cls)
   dic.append("title",title)
   dic.append("data",imgFile)
   dic.append("changFlag",changFlag)
   ajax(dic,"center.php","POST",js=false,insertHTML)
   
  }
  else
  {
   alert("请选择文件")
  }
 }
}



//显示状态
function showStatus(info="测试",time=2000,showing="no")
{
 var status=document.getElementById("status")
 status.style.display="block"
 status.innerText="状态:"+info
 statusToCenter()
 if(showing=="no")
 {
  setTimeout(function()
  {
   status.style.display="none"
  },time)
 }
 
}

//工具行数判断是否有某个属性,没有就返回false
function getStyle(ele,string)
{
 if(string==1)
 {
  string="width"
 }
 if(string==2)
 {
  string="height"
 }
 if(string==3)
 {
  string="display"
 }
 if(ele.style[string]==undefined||ele.style[string].length==0||ele.style[string]=="none")
 {
  return false
 }
 else
 {
  return true
 }
}


//这里进行表格的整形
function dealTableSize(table)
{

   var tr=table.getElementsByTagName("tr")
   var th=tr[0].getElementsByTagName("th")
   var tableBox=table.parentNode

   var columBox=tableBox.getElementsByClassName("columBox")[0]
   var rowBox=tableBox.getElementsByClassName("rowBox")[0]
   var columLi=columBox.getElementsByTagName("li")
   var rowLi=rowBox.getElementsByTagName("li")
   var wC=1
   
   var hC=0
   var thWList=[]
   var colgroup=table.getElementsByTagName("colgroup")[0]
   if(colgroup!=null)
   {
   colgroup.parentNode.removeChild(colgroup)
   }

   //进行宽度调整
   for(var i=0;i<th.length;i++)
   {
      var sW=parseInt(th[i].style.width.replace("px",""))
      var oW=Math.ceil(th[i].offsetWidth)

      var getW=0
      if(oW>sW||isNaN(sW))
      {
      getW=oW
      }
      else
      {
      getW=sW
      }
      thWList.push(getW)
      wC+=getW
   }

   for(i in thWList)
   {
      for(var trC=0;trC<tr.length;trC++)
      {
         if(trC==0)
         {
            columLi[i].style.width=thWList[i]+"px"
            columLi[i].innerText=parseInt(i)+1
            th[i].style.width=thWList[i]+"px"
            th[i].removeAttribute("width")
         }
         else
         {
            tr[trC].getElementsByTagName("td")[i].style.width=thWList[i]+"px"
            tr[trC].getElementsByTagName("td")[i].removeAttribute("width")
         }
         tr[trC].removeAttribute("width")
         //tr不需要样式
         tr[trC].removeAttribute("style")
      }
   }

   editeTable(table,columLi,"colume")



   // 进行高度调整
   for(var j=0;j<tr.length;j++)
   {  
      var thTd=tr[j].children
      var sH=parseInt(thTd[0].style.height.replace("px",""))
      var oH=Math.ceil(thTd[0].offsetHeight)
      
      var getH=0
      if(oH>sH||isNaN(sH))
      {
         getH=oH
      }
      else
      {
         getH=sH
      }
     
      rowLi[j].innerText=j+1
      rowLi[j].style.height=getH+"px"
      rowLi[j].style.lineHeight=getH+"px"
      for(var t=0;t<thTd.length;t++)
      {
         thTd[t].style.height=getH+"px"
         thTd[t].removeAttribute("height")
      }
      hC+=getH
      tr[j].removeAttribute("height")
      editeTable(table,rowLi,"row")
   }

   table.removeAttribute("width")
   table.removeAttribute("height")
   table.style.width=wC+"px"
   columBox.style.width=wC+"px"
   tableBox.style.width=wC+51+"px"
   table.style.height=hC+"px"
   rowBox.style.height=hC+"px"
   tableBox.style.height=hC+35+"px"
}


//这里实现表格的处理
function dealTable(table,index,addHLip,flag)
{


 if(flag=="preAddColume")
 {
  addColum(table,index,addHLip,"pre")
 }
 if(flag=="hdAddColume")
 {  
  addColum(table,index,addHLip,"hd")
 }
 if(flag=="preAddRow")
 {
  addRow(table,index,"pre")
 }
 if(flag=="hdAddRow")
 {
  addRow(table,index,"hd")
 }



 if(flag=="selectColume")
 {

   
  var tr=table.getElementsByTagName('tr')
  var tableBox=table.parentNode
  var columBox=tableBox.getElementsByClassName("columBox")[0]
  var columLi=columBox.getElementsByTagName("li")

  var th=tr[0].getElementsByTagName("th")
  var cha=addHLip-parseInt(th[index].style.width.replace("px",""))

  for(var i=0;i<tr.length;i++)
  {
   if(i==0)
   {
    th[index].style.width=addHLip+"px"
    columLi[index].style.width=addHLip+"px"
    tableBox.style.width=parseInt(tableBox.style.width.replace("px",""))+cha+"px"
    columBox.style.width=parseInt(columBox.style.width.replace("px",""))+cha+"px"
    table.style.width=parseInt(table.style.width.replace("px",""))+cha+"px"
   }
   else
   {
    tr[i].getElementsByTagName("td")[index].style.width=addHLip+"px"
   }
   
  }
 }

 if(flag=="selectRow")
 {
  var tableBox=table.parentNode
  var tr=table.getElementsByTagName('tr')
  var thTd=tr[index].children
  var rowBox=tableBox.getElementsByClassName("rowBox")[0]
  var rowLi=rowBox.getElementsByTagName("li")
  var cha=addHLip-parseInt(thTd[0].style.height.replace("px",""))
  for(var i=0;i<thTd.length;i++)
  {
      thTd[i].style.height=addHLip+"px"

  }
  rowLi[index].style.height=addHLip+"px"
  tableBox.style.height=parseInt(tableBox.style.height.replace("px",""))+cha+5+"px"
  table.style.height=parseInt(table.style.height.replace("px",""))+cha+"px"
  rowBox.style.height=parseInt(rowBox.style.height.replace("px",""))+cha+"px"
  
 }
 if(flag=="deleColume")
 {

  var tableBox=table.parentNode
  var columBox=tableBox.getElementsByClassName("columBox")[0]
  var columLi=columBox.getElementsByTagName("li")
  var tr=table.getElementsByTagName("tr")
  var th=tr[0].getElementsByTagName("th")
  var columLiW=parseInt(th[index].style.width.replace("px",""))
  for(var i=0;i<tr.length;i++)
  {
   if(i==0)
   {
    columBox.removeChild(columLi[index])
    tr[i].removeChild(th[index])
   }
   else
   {
    tr[i].removeChild(tr[i].getElementsByTagName("td")[index])
   }
  }
  tableBox.style.width=parseInt(tableBox.style.width.replace("px",""))-columLiW+"px"
  columBox.style.width=parseInt(columBox.style.width.replace("px",""))-columLiW+"px"
  table.style.width=parseInt(table.style.width.replace("px",""))-columLiW+"px"
 }


 if(flag=="deleRow")
 {
  
  var tableBox=table.parentNode
  var rowBox=tableBox.getElementsByClassName("rowBox")[0]
  var rowLi=rowBox.getElementsByTagName("li")
  var tbody=table.getElementsByTagName("tbody")[0]
  var tr=tbody.getElementsByTagName("tr")
  var thTd=tr[index].children

  var rowLiH=parseInt(thTd[0].style.height.replace("px",""))

  rowBox.removeChild(rowLi[index])
  tbody.removeChild(tr[index]) 

  rowBox.style.height=parseInt(rowBox.style.height.replace("px",""))-rowLiH+"px"
  tableBox.style.height=parseInt(tableBox.style.height.replace("px",""))-rowLiH+5+"px"
  table.style.height=parseInt(table.style.height.replace("px",""))-rowLiH+"px" 
 }
 

 function addColum(table,index,addHLip,flag="pre")
 {

  var tr=table.getElementsByTagName("tr")
  var tableBox=table.parentNode
  var columBox=tableBox.getElementsByClassName("columBox")[0]

  var tdC=tr[0].getElementsByTagName("td")
  var lieList=[]
  for(var i=0;i<tr.length;i++)
  { 
   for(var j=0;j<addHLip;j++)
   {
    if(i==0)
    {
     var newEle=document.createElement("th")
     var newLi=document.createElement("li")

     newEle.style.width="50px"
     newLi.style.width="50px"
     newLi.style.background="yellow"
     if(flag=="pre")
     {
      
      tr[i].insertBefore(newEle,tr[i].getElementsByTagName("th")[index])
      columBox.insertBefore(newLi,columBox.getElementsByTagName("li")[index])
     }
     else
     {
      tr[i].insertBefore(newEle,tr[i].getElementsByTagName("th")[index].nextSibling)
      columBox.insertBefore(newLi,columBox.getElementsByTagName("li")[index].nextSibling)
     }
     tableBox.style.width=parseInt(tableBox.style.width.replace("px",""))+50+"px"
     table.style.width=parseInt(table.style.width.replace("px",""))+50+"px"
     columBox.style.width=parseInt(columBox.style.width.replace("px",""))+50+"px"
     
    }
    else
    {
     var newEle=document.createElement("td")
     newEle.style.width="50px"
     if(flag=="pre")
     {
      tr[i].insertBefore(newEle,tr[i].getElementsByTagName("td")[index])
     }
     else
     {
      tr[i].insertBefore(newEle,tr[i].getElementsByTagName("td")[index].nextSibling)
     }
    }

   }
   
  }
  
 }

 function addRow(table,index,flag)
 {
  var tr=table.getElementsByTagName("tr")
  var tableBox=table.parentNode
  var rowBox=tableBox.getElementsByClassName("rowBox")[0]
  var td=tr[index].getElementsByTagName("td")
  if(index==0)
  {
   alert("第一行不能选择，请选择第二行")
   return
  }
  for(var i=0;i<addHLip;i++)
  {
   var newTr=document.createElement("tr")
   var newLi=document.createElement("li")
   newTr.style.height="30px"
   newLi.style.background="yellow"

   for(var j=0;j<td.length;j++)
   {
    var newTd=document.createElement("td")
    newTr.appendChild(newTd)
   }

   if(flag=="pre")
   {
    if(index==0)
    {
     alert("第一行是标题行，不能在此前添加")
     return
    }
    tr[index].parentNode.insertBefore(newTr,tr[index])
    rowBox.insertBefore(newLi,rowBox.getElementsByTagName("li")[index])
    
   }
   if(flag=="hd")
   {
    tr[index].parentNode.insertBefore(newTr,tr[index].nextSibling)
    rowBox.insertBefore(newLi,rowBox.getElementsByTagName("li")[index].nextSibling)
   }
   tableBox.style.height=parseInt(tableBox.style.height.replace("px",""))+35+"px"
   table.style.height=parseInt(table.style.height.replace("px",""))+30+"px"
   rowBox.style.height=parseInt(rowBox.style.height.replace("px",""))+30+"px"

  }
 }
   dealTableSize(table)
}


//初始化表格尺寸和单元格点击
function initTalbe()
{
  

 var allTable=document.getElementsByTagName("table")
 var parent=""
 var textArea=document.getElementById("textArea")

 for(var i=0;i<allTable.length;i++)
 {

  parent=allTable[i].parentNode
  allTable[i].style.tableLayout="fixed"
  if(parent.className=="tableBox")
  {

      // allTable[i].style.height=allTable[i].offsetHeight+"px"
      var columBox=parent.getElementsByClassName("columBox")[0]
      var rowBox=parent.getElementsByClassName("rowBox")[0]
      if(columBox!=null)
      {
       columBox.style.width=allTable[i].offsetWidth+"px"
      }
       if(rowBox!=null)
      {
       rowBox.style.height=allTable[i].offsetHeight+"px"
      }

       parent.style.height=allTable[i].offsetHeight+30+"px"
       

  }
  
  if(parent.className!="tableBox")
  { 
     var now=new Date()
     var year = now.getFullYear();
     var month = now.getMonth() + 1
     var day = now.getDate()
     var hours = now.getHours()
     var minutes = now.getMinutes()
     var seconds = now.getSeconds()
     var time=""+year+month+day+hours+minutes+seconds

   var tableBox=document.createElement("div")
   var columBox=document.createElement("ul")
   var rowBox=document.createElement("url")
   
   var table=allTable[i]
   var tr=allTable[i].getElementsByTagName("tr")
   var td=allTable[i].getElementsByTagName("td")
   var tr0tdTh=tr[0].getElementsByTagName("td")
   var tr0tdThL=0
   var trC=tr.length

   //如果表格是唯一的一行，第一次表格第一行是td，但是经过
   //优化后变成了th，所以第一次获取td是对的，但是撤销后再
   // 返回就变成了th，所以错误，这里要考虑全部情况
   if(tr0tdTh.length==0)
   {  
      tr0tdTh=tr[0].getElementsByTagName("th")
   }
   tr0tdThL=tr0tdTh.length
   var addW=0
   var addH=0

   tableBox.className="tableBox"
   columBox.className="columBox"
   table.className="table"
   table.id="table"+time
   rowBox.className="rowBox"
   
            
     
    var getW=allTable[i].getAttribute("width")
    var getH=allTable[i].getAttribute("height")
    if(getW!=null)
    {
     allTable[i].style.height=getW+"px"
    }
    if(getH!=null)
    {
     allTable[i].style.height=getH+"px"
    }
    
   
   for(var r=0;r<r.length;r++)
   {
    var getW=tr[r].getAttribute("width")
    var getH=tr[r].getAttribute("height")
    var trStyle=tr[r].getAttribute("tr")
    
     if(getW!=null)
     {
      tr[r].style.width=getW+"px"
     }
     if(getH!=null)
     {
      tr[r].style.height=getH+"px"
     }    
    
   }

   for(var d=0;d<td.length;d++)
   {
    var getW=td[d].getAttribute("width")
    var getH=td[d].getAttribute("height")
    var tdStyle=td[d].getAttribute("style")
    td[d].style.borderWidth="1px"
    td[d].style.borderStyle="dashed"
    td[d].style.borderColor="#ccc"
    td[d].style.textWrap="wrap"
    td[d].style.whiteSpace="wrap"; 
   
    if(getW!=null)
    {
     td[d].style.width=getW+"px"
    }

    if(getH!=null)
    {
     td[d].style.height=getH+"px"
    }
    
   }

   //行索引 
   for(var rowi=0;rowi<trC;rowi++)
   {
    var li=document.createElement("li")
    li.innerText=rowi+1
    li.style.height=tr[rowi].offsetHeight+"px"
    li.style.width="50px"
    li.style.lineHeight=tr[rowi].offsetHeight+"px"
    li.setAttribute("contenteditable","false")
    rowBox.appendChild(li)
   }

   // 列索引
   for(var columi=0;columi<tr0tdThL;columi++)
   {
    var li=document.createElement("li")
    li.innerText=columi+1
    li.style.width=tr0tdTh[columi].offsetWidth+"px"
    // li.style.width=tr0td[columi].style.width
    li.style.height="30px"
    li.setAttribute("contenteditable","false")
    columBox.appendChild(li)
    
   }

   


   var columW=parseInt(allTable[i].style.width.replace("px","").replace("pt",""))
   var rowH=parseInt(allTable[i].style.height.replace("px","").replace("pt",""))
   
   tableBox.style.width=allTable[i].offsetWidth+51+"px"
   tableBox.style.height=allTable[i].offsetHeight+35+"px"


   columBox.style.width=(allTable[i].offsetWidth)+"px"
   columBox.style.height="30px"
   rowBox.style.height=allTable[i].offsetHeight+"px"
   rowBox.style.width="50px"


   
   

   //第一行变成Th
   for(var thi=tr0tdThL-1;thi>-1;thi--)
   {
      var th=document.createElement("th")
       th.className="0-"+thi
       th.setAttribute("style",tr0tdTh[thi].getAttribute("style"))
       th.style.borderBottom="3px solid black"
       th.innerHTML=tr0tdTh[thi].innerHTML
       tr0tdTh[thi].parentNode.replaceChild(th, tr0tdTh[thi]);
   }
   tableBox.appendChild(columBox)
   tableBox.appendChild(allTable[i])
   tableBox.appendChild(rowBox)
   
   
  //如果是老的数据表格那么加载的时候由于编辑框还没有
   // 聚焦所有不能直接插入，同时就算第一次聚焦也是
   // 会聚焦到第一行，所以这里用插入。
   if(document.activeElement!=textArea)
   {
      var p=document.createElement("p")
      p.innerHTML="<br>"
      parent.insertBefore(tableBox,allTable[i])
      tableBox.after(p)
      p.after(p)
   }
   else
   {
      //表格后面要添加两个p否则会出现问题
      execute("insertHTML",tableBox.outerHTML+"<p><br></p><p><br></p>")
   }
  }
 }

 //给张贴的表格添加尺寸(解决原来数据库的问题)
 var allTableBox=document.getElementsByClassName("tableBox")
 for(var t=0;t<allTableBox.length;t++)
 {   

   var tableBox=allTableBox[t]
   var columBox=tableBox.getElementsByClassName("columBox")[0]
   var columLi=columBox.getElementsByTagName("li")
   var table=tableBox.getElementsByTagName("table")[0]

   var rowBox=tableBox.getElementsByClassName("rowBox")[0]
   var rowLi=rowBox.getElementsByTagName("li")

   var th=table.getElementsByTagName("th")
   var tr=table.getElementsByTagName("tr")
   var td=table.getElementsByTagName("td")

   var hang=tr.length
   var lie=th.length


  // //下面是如果没有原始的尺寸这里就先添加原始的尺寸
  if(!getStyle(tableBox,1))
  {  
   tableBox.style.width=table.offsetWidth+51+"px"
   table.style.width=table.offsetWidth+"px"
   columBox.style.width=table.offsetWidth+"px"
   rowBox.style.width=50+"px"

   for(var t=0;t<td.length;t++)
   {
    td[t].style.width=td[t].offsetWidth+"px"
   }

   for(var h=0;h<th.length;h++)
   {
    th[h].style.width=th[h].offsetWidth+"px"
   }
  }
        
  if(!getStyle(tableBox,2))
  {
   tableBox.style.height=table.offsetHeight+35+"px"
   table.style.height=table.offsetHeight+"px"
   columBox.style.height=30+"px"
   rowBox.style.height=table.offsetHeight+"px"
   for(var tc=0;tc<tr.length;tc++)
   {
    tr[tc].style.height=tr[tc].offsetHeight+"px"
   }
   for(var h=0;h<th.length;h++)
   {
    th[h].style.height=th[h].offsetHeight+"px"
   }
  }

   // 单元格有iput编辑功能
   tdip(tr)
   //下面函数里已经有修改功能
   dealTableSize(table)
   // 这里是边框修改表格的功能
   //editeTable(table,columLi,"colume")
   //editeTable(table,rowLi,"row")
 }

}



//单元格能够使用input进行编辑
function tdip(tr)
{
 //这里是动态修改单元格td的
 var ele=""
  for(var l=0;l<tr.length;l++)
  {
   var trD=tr[l].getElementsByTagName("td")
   for(var t=0;t<trD.length;t++)
    { 
     trD[t].addEventListener("click",function(e)
     {
      ele=this
      document.addEventListener("keydown",htmlToText)
     })
    }
  }

 //这里是动态修改列名th的
 var trH=tr[0].getElementsByTagName("th")
 for(var t=0;t<trH.length;t++)
  { 
   trH[t].addEventListener("click",function()
   {
     ele=this
     document.addEventListener("keydown",htmlToText)
     
    })
  }
  

  //解决在单元格粘贴表格问题
  function htmlToText(e)
  {
      var ctrl=e.ctrlKey
        var meta=e.metaKey
       if((ctrl||meta)&&e.key=="v")
       {  
        setTimeout(function()
        {
         ele.innerHTML=ele.innerText
         setTimeout(function()
            {
                  
           document.removeEventListener("keydown",htmlToText)
            },200)
         
        },100)
        
       }
  }
}


//这里是边框修改表格的功能
function editeTable(table,li,flag)
{


    
 var changeTable=document.getElementById("changeTable")
 var tbEditCancel=document.getElementById("tbEditCancel")
 var liC=0
 tbEditCancel.onclick=function()
 {
  if(getStyle(changeTable,3))
  {
   changeTable.style.display="none"
   while(indexList.length!=0)
   {
    indexList.pop().style.background="yellow"
   }
  }
 }
 

 for (var i=0;i<li.length; i++)
 {
  li[i].onclick=function()
  {

          
   while(indexList.length!=0)
   {
    indexList.pop().style.background="yellow"
   }
   this.style.background="red"
   indexList.push(this)
   changeTable.style.display="block"
   moveBox(changeTable)
   changeTableUI()

   var index=parseInt(this.innerText)-1
   var addHLip=document.getElementById("addHLip")
   var preAddButton=document.getElementById("preAddButton")
   var hdAddButton=document.getElementById("hdAddButton")
   var sizeY=document.getElementById("sizeY")
   var tableDele=document.getElementById("tableDele")
   var tbEditCancel=document.getElementById("tbEditCancel")
   var deleTableButton=document.getElementById("tableDele")

   preAddButton.onclick=function()
   {   
    if(flag=="colume")
    {
     dealTable(table,index,parseInt(addHLip.value),"preAddColume")
    }
    if(flag=="row")
    {
     dealTable(table,index,parseInt(addHLip.value),"preAddRow")
    }
    index+=parseInt(addHLip.value)
   }

   hdAddButton.onclick=function()
   {
    if(flag=="colume")
    {
     
        dealTable(table,index,parseInt(addHLip.value),"hdAddColume")
     
    }
    if(flag=="row")
    {
     dealTable(table,index,parseInt(addHLip.value),"hdAddRow")
    }
   }


   sizeY.onclick=function() 
   {
    var setWHip=parseInt(document.getElementById("setWHip").value)
    if(setWHip<5||isNaN(setWHip))
    {
     alert("高度和宽度不能小于5px")
     return
    }

    if(flag=="colume")
    {
     
     dealTable(table,index,setWHip,"selectColume")
    }
    if(flag=="row")
    {
     dealTable(table,index,setWHip,"selectRow")
    }
   }

   deleTableButton.onclick=function()
   {
                 
    if(flag=="colume")
    {
     var columeBox=table.parentNode.parentNode.getElementsByClassName("columBox")
     var columeLi=columeBox[0].getElementsByTagName("li")
     if(li.length<2)
     {
      alert("不能再进行删除，要留最后一列")
      return
     }

     dealTable(table,index,0,"deleColume")
    }
    if(flag=="row")
    {
     var tr=table.getElementsByTagName("tr")
     if(tr.length<3)
     {
      alert("必须剩余标题行和普通行")
      return
     }

     if(index<1)
     {
      alert("第一行不能删除")
      return
     }
     
     dealTable(table,index,0,"deleRow")
     
     
    }
   }
  }
 }
}

//进行页面监听确保页面里有空白的<p><br></p>
function setP()
{
 var textArea=document.getElementById("textArea")
 textArea.addEventListener("input",function(){
   // 解决张贴的表格格式问题,要延时解决插入表格格式问题
   setTimeout(function(){
      initTalbe()
   },100)
 })
 
 //初始化是检查
 appendP()
}

function appendP()
{
  var textArea=document.getElementById("textArea")
  var child=textArea.lastChild
  if(child==null||child.outerHTML!="<p><br></p>")
  {
   var p=document.createElement("p")
   // p.innerHTML="<font size='"+fontS+"'><br></font>"
   p.innerHTML="<br>"
   textArea.appendChild(p)
   //innerHTML会修改光标位置
   // textArea.innerHTML+="<p><br></P>"
   // textArea.focus()
   // execute("insertHTML",p.outerHTML)
   // execute("insertHTML",p2.outerHTML)
  }
}


//调整页面 
function showUI()
{  
 //让工具箱居中
 function toolToCneter()
 {
  var toolBox=document.getElementById("toolBox")
  var toCenter=document.getElementById("toCenter")
  w=Math.ceil(toolBox.offsetWidth)
  if(!phone)
  {
   count=parseInt(w/80)
   toCenter.style.width=count*80+"px"
  }
  else
  {
   count=parseInt(w/200)
   toCenter.style.width=count*200+"px"
  }
  
 }
 toolToCneter()
 window.addEventListener("resize",function()
 {
  toolToCneter()
  imgToCenter()
  statusToCenter()
  tableInsertToCenter()
  fontSizeToCenter()
  fonteColorBoxToCenter()
  backgroundColorBoxToCenter()
  changeTableUI()
  lineHeightBoxToCenter()
  foneWidthBoxToCenter()
 })
 

    imgToCenter()
    statusToCenter()
    tableInsertToCenter()
    fontSizeToCenter()
    fonteColorBoxToCenter()
    backgroundColorBoxToCenter()
    changeTableUI()


    //初始化表格:由于这个函数要多次外侧调用所以放在外面定义
    initTalbe()
    lineHeightBoxToCenter()
    foneWidthBoxToCenter()

 
}

//显示代码
function toHtml()
{
 var flag=false
 var html=document.getElementById("html")
 var textArea=document.getElementById("textArea")
 html.onclick=function()
 {
  if(flag==false)
  {
   textArea.innerText=textArea.innerHTML.replace(/\n/ig,"")
   flag=true
   html.style.color="#ccc"
   closeOtherAlter("")
  }
  else if(flag==true)
  {
   textArea.innerHTML=textArea.innerText
   flag=false
   html.style.color="black"
  }
 }
}


/**********************以下是居中函数****************/
//让图片预览框居中
function imgToCenter()
{
 var imgbox=document.getElementById("showImgBox")
 var viw=Math.ceil(document.getElementById("popBox").offsetWidth)
 var x=(viw-imgbox.offsetWidth)/2
 imgbox.style.left=x+"px"
 if(imgbox.style.top=="")
 {
  imgbox.style.top="20px"
 }
}
function lineHeightBoxToCenter()
{
   var lineHeightBox=document.getElementById("lineHeightBox")
   var popBox=document.getElementById("popBox")
   var viw=Math.ceil(popBox.offsetWidth)
   var x=(viw-150)/2
   lineHeightBox.style.left=x+"px"
   if(lineHeightBox.style.top=="")
   {
     lineHeightBox.style.top="180px"
   }
}

function foneWidthBoxToCenter()
{
   var foneWidthBox=document.getElementById("foneWidthBox")
   var popBox=document.getElementById("popBox")
   var viw=Math.ceil(popBox.offsetWidth)
   var x=(viw-150)/2
   foneWidthBox.style.left=x+"px"
   if(foneWidthBox.style.top=="")
   {
     foneWidthBox.style.top="180px"
   }
}



//让插入表格居中
function tableInsertToCenter()
{
 var insertTableBox=document.getElementById("insertTableBox")
 var viw=Math.ceil(popBox.offsetWidth)
 var x=(viw-insertTableBox.offsetWidth)/2
 insertTableBox.style.left=x+"px"
}

//让字体大小居中
function fontSizeToCenter()
{
 var fontSizeBox=document.getElementById("fontSizeBox")
 var viw=Math.ceil(document.getElementById("popBox").offsetWidth)
 var x=(viw-fontSizeBox.offsetWidth)/2
 fontSizeBox.style.left=x+"px"
 if(fontSizeBox.style.top=="")
 {
   fontSizeBox.style.top="20px"
 }
}


//让前景色居中
function fonteColorBoxToCenter()
{
 var fonteColorBox=document.getElementById("fonteColorBox")
 var viw=Math.ceil(document.getElementById("popBox").offsetWidth)
 var x=(viw-fonteColorBox.offsetWidth)/2
 fonteColorBox.style.left=x+"px"
 if(fonteColorBox.style.top=="")
 {
  fonteColorBox.style.top="20px"
 }
}


//让背景色居中
function backgroundColorBoxToCenter()
{
 var backgroundColorBox=document.getElementById("backgroundColorBox")
 var viw=Math.ceil(document.getElementById("popBox").offsetWidth)
 var x=(viw-backgroundColorBox.offsetWidth)/2
 backgroundColorBox.style.left=x+"px"
 if(backgroundColorBox.style.top=="")
 {
  backgroundColorBox.style.top="20px"
 }
}


//让状态居中
function statusToCenter()
{
 var ele=document.getElementById("status")
 var viw=Math.ceil(document.getElementsByTagName("body")[0].offsetWidth)
 var x=(viw-ele.offsetWidth)/2
 ele.style.left=x+"px"
 
}


//让表格弹出框居中
function changeTableUI()
{
 var changeTable=document.getElementById("changeTable")
 var viw=Math.ceil(document.getElementById("popBox").offsetWidth)
 var x=(viw-changeTable.offsetWidth)/2
 textArea=document.getElementById("textArea")
 changeTable.style.left=x+"px"

 if(changeTable.style.top=="")
 {
  changeTable.style.top=20+"px"
 }
}


//点击弹出框关闭其它弹出框
function closeOtherAlter(id)
{
 var obList=["fonteColorBox","backgroundColorBox",
          "fontSizeBox","insertTableBox",
          "showImgBox","changeTable","lineHeightBox","foneWidthBox"]
 for(var i=0;i<obList.length;i++)
 {
  if(id.replace(/\s+/ig,"")!=obList[i])
  {
   document.getElementById(obList[i]).style.display="none"
  }
 }
} 


//点击保存
function save()
{
 var s=document.getElementById("save")
 var html=document.getElementById('html')
 var textArea=document.getElementById("textArea")
 
 
 s.onclick=function()
 {
  if(html.style.color=="rgb(204, 204, 204)")
  {
   showStatus("请切换到输入文本模式",1600)
   return
  }
  else
  {   
   var fileList=[]
   var img=textArea.getElementsByTagName("img")
   var video=textArea.getElementsByTagName("video")
   var a=textArea.getElementsByTagName("a")

   for(var i=0;i<img.length;i++)
   {
      if(img[i].getAttribute("src")!=null)
      {
         fileList.push(img[i].getAttribute("src").replace(filePath,""))
      }
    
   }
   for(var i=0;i<video.length;i++)
   {
      if(video[i].getAttribute("src")!=null)
      {
         fileList.push(video[i].getAttribute("src").replace(filePath,""))
      }
    
   }

   for(var i=0;i<a.length;i++)
   {

      if(a[i].getAttribute("href")!=null)
      {
         fileList.push(a[i].getAttribute("href").replace(filePath,""))
      }
    
   }
   var title=getTiltle()
   var cls=getCls()
   if(title!=false&&cls!=false)
   {
    var dic={"flag":"saveText","cls":cls,title,"data":textArea.innerHTML,
     "changFlag":changFlag,"fileName":fileList,"oldCls":oldCls,"oldTitle":oldTitle,"noCheckSave":noCheckSave}
    
    ajax(dic,"center.php","POST",js=true,function(e)
    {
     if(e.trim()=="saveOk")
     {   
      showStatus("保存成功",2000)
      changFlag="yes"
      oldCls=cls
      oldTitle=title
      changeUrlParams(changFlag)
     }
     else if(e.trim()=="changButNoFile")
     {
      showStatus("修改文件但是系统中没有文件:"+cls+"#-#"+title+".txt")
     }
     else if(e.trim()=="enterButHavedFile")
     {
      showStatus("导入但是系统中已有文件:"+cls+"#-#"+title+".txt")
     }
    })
   }
  }
 }
}

//获得标题名称

function getTiltle()
{
 var contentText=textArea.innerText
 var sp=contentText.split("\n")
 var title=sp[0].replace(/\s+/ig,"")
 var reg=title.match(/[^a-zA-Z\u4e00-\u9fa5\d\(\)\[\]（）【】：“”"‘’'-]/)
 if(title.length==0)
 {
  alert("标题不能为空")
  title=false
 }
 if(reg!=null)
 {   
  alert("标题有非法字符"+reg[0])
  title=false

 }
 return title
}

//获取类
function  getCls()
{
 var cls=document.getElementById("cls").value
 var cls=cls.replace(/\s+/ig,"")
 var reg=cls.match(/[^a-zA-Z\u4e00-\u9fa5\d\(\)\[\]（）【】：“”"‘’']/)
 if(cls.length==0)
 {
  alert("类型不能为空")
  title=false
 }
 if(reg!=null)
 {   
  alert("类型有非法字符"+reg[0])
  title=false

 }
 return cls
}

// ajax函数
function ajax(dic,url,method,js=true,fun="")
{
 var xhr=new XMLHttpRequest()
 xhr.open(method,url,true)

  
  xhr.onreadystatechange = function(e)
 
 {
  
  if(xhr.readyState == 4&&xhr.status==200)
  {
   console.log(xhr.response)
   if(fun!="")
   {
    fun(xhr.response)
   }
  }
 }

 if(js)
 {
  xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
  xhr.send(JSON.stringify(dic))
  
 }
 else
 {
  uploadPercent=0
  var flag=1
  xhr.upload.addEventListener("progress",function(e)
  {   
   if(flag==1)
   {
    uploadPercent=Number(((e.loaded/e.total)*100).toFixed(2))
    showStatus("已经上传:"+uploadPercent+"%",2000,"yes")
    flag=0
   }
   
   setTimeout(function()
   {
    uploadPercent=Number(((e.loaded/e.total)*100).toFixed(2))
    if(uploadPercent<100)
    {   
     showStatus("已经上传:"+uploadPercent+"%",2000,"yes")
    }
    else
    {
     showStatus("已经上传:"+uploadPercent+"%",2000,"yes")
     showStatus("加载中.....",2000,"yes")
     
    }
    
    
   },1000)
   
  })
  xhr.send(dic)
 }
 
}

//移动表格编辑框
function moveBox(ele)
{
 
    var y=0
    var x=0
    var oldx=0
    var oldy=0
    var container=document.getElementById("container")
 if(ele!=null)
 {
  ele.addEventListener("mousedown",downFunction)
  function downFunction(e)
  {
   y=e.clientY
   x=e.clientX
   oldx=parseInt(ele.style.left.replace("px",""))
      oldy=parseInt(ele.style.top.replace("px",""))
   document.addEventListener("mousemove",moveFunction)
   document.addEventListener("mouseup",function()
   {
    document.removeEventListener("mousemove",moveFunction)
   })
  }
  

  function moveFunction(e)
  {  
   var newx=oldx+e.clientX-x
   var newy=oldy+e.clientY-y
   var maxx=container.offsetWidth
   var maxy=container.offsetHeight
   if(newx>0&&newx<maxx-ele.offsetWidth)
   {
     ele.style.left=newx+"px"
   }
   
   if(newy>0&&newy<maxy-ele.offsetHeight-180)
   {
    ele.style.top=newy+"px"
   }
  }
 }
}

//监听键盘
function listenKey()
{
 document.addEventListener("keydown",function(e)
 {
  var ctrl=e.ctrlKey
  var meta=e.metaKey
  var shift=e.shiftKey
  var alt=e.altKey
  //工具框固定
  if((ctrl||meta)&&e.key=="i")
  {
      e.preventDefault()
      var toolBox=document.getElementById("toolBox")
      var container=document.getElementById("container")
      if(toolBox.style.position=="relative"||toolBox.style.position=="")
      {
       toolBox.style.position="fixed"
       toolBox.style.zIndex="100"
       toolBox.style.left=(container.offsetWidth-toolBox.offsetWidth)/2+"px"
      }
      else
      {
       toolBox.style.position=""
      }
  }
  //保存快捷键 
  else if((ctrl||meta)&&e.key=="s")
  {   
      e.preventDefault()
      var s=document.getElementById("save")
      s.click()
  }
  
  //如果换行或删除后面没有空白行就进行添加
  else if(e.key=="Enter"||e.key=="Backspace")
  {   
      setTimeout(function()
      { 
       appendP()
      },500)
  }
 })
}

//编辑页面拖拉文件上传

function editeUpLoadFile()
{
 var textArea=document.getElementById("textArea")
 

 textArea.addEventListener("dragover",function(e)
 {
  e.preventDefault()
 })

 textArea.addEventListener("drop",function(e)
 {
     e.preventDefault()
     if(textAreaDragFlage=="no")
     { console.log(textAreaDragFlage)
         imgFile=e.dataTransfer.files[0]
         var dic=new FormData()
         //如果标题为空这里会弹出警告，并返回false
         var title=getTiltle()
         var cls=getCls()
         if(title==false||cls==false)
         {
         alert("请先输入标题或分类")
         return
         }

         dic.append("flag","upload")
         dic.append("cls",cls)
         dic.append("title",title)
         dic.append("data",imgFile)
         dic.append("changFlag",changFlag)
         ajax(dic,"center.php","POST",js=false,insertHTML)
     }
//flag=true
 })
}

//在编辑框内拖拉文件不触发上传初始化
function textAreaDragImgNoUpInit()
{  
   var video=document.getElementsByTagName("video")
   var img=document.getElementsByTagName("img")
   var a=document.getElementsByTagName("a")
   
   for(var v=0;v<video.length;v++)
   {
      Fun(video[v])
   }
   for(var i=0;i<img.length;i++)
   {
      Fun(img[i])
      //修改页面初始化不保存
     
   }
   for(var ai=0;ai<a.length;ai++)
   {
      Fun(a[ai])
   }
   
   function Fun(ele)
   {  

      ele.addEventListener("mousedown",function()
      {
         textAreaDragFlage="yes"
      })
      ele.addEventListener("mouseup",function()
      {
         textAreaDragFlage="no"
      })
   }
   
}


//鼠标按下文件，在编辑框内拖拉文件不触发上传
function FileMouseD()
{
   textAreaDragFlage="yes"
}
//鼠标抬起，在编辑框内拖拉文件触发上传
function FileMouseU()
{
   textAreaDragFlage="no"
}

//插入文件
function insertHTML(url)
{
 var textArea=document.getElementById("textArea")
 var url=url.trim()
 var showImgBox=document.getElementById("showImgBox")
 var save=document.getElementById("save")
 
 textArea.focus()
  if(url.includes("数据库中已有文件"))
  {
   alert(url)
   return
  }
  if(url.includes("数据库中没有文件"))
  {
   alert(url)
   return
  }


 if (url=="uplaodFaile") 
 {
  alert("文件上传失败，请检查")
  return
 }

 if(imgFile.type.includes("image"))
 {
   //一直显示加载中知道最后一个图片完成:这里每次要清零
   tempCimg=0
   //如果有图片上传就不是第一次进入
   firstEnter="no"
   execute("insertHTML","<p style='text-align:center;' ><img onmousedown='FileMouseD()' onmouseup='FileMouseU()' onload='imgLoad()' style='width:80%;border:1px solid #ccc;' src='"+filePath+url+"'></p>")
     showImg.src="img/showImg.jpg"
 }
 else if(imgFile.type.includes("video"))
 {
  execute("insertHTML","<p style='text-align:center;'><video onmousedown='FileMouseD()' onmouseup='FileMouseU()' controls style='width:80%;border:1px solid #ccc;' src='"+filePath+url+"'></video></p>")
  save.click()
 }
 else
 {
  execute("insertHTML","<p><a onmousedown='FileMouseD()' onmouseup='FileMouseU()' style='width:80%;border:1px solid #ccc;' href='"+filePath+url+"'>"+imgFile.name+"</a></p>")
  save.click()
 }
 
 showImgBox.style.display="none"
 
}
//图片加载进度
function imgLoad()
{
  var save=document.getElementById("save")
  var CImg=document.getElementById("textArea").getElementsByTagName("img").length

  tempCimg+=1
  //修改时第一次进入这个页面就不用保存
  
  if(tempCimg==CImg&&firstEnter=="no")
  {   
      showStatus("加载完成",1000,"yes")
      setTimeout(function()
      {
         save.click()
      },1000)
  } 
}

//判断是否是修改还是添加
function loadData()
{
   oldCls=document.getElementById("oldCls").value
   oldTitle=document.getElementById("oldTitle").value
   changFlag=document.getElementById("subEd").value
   var contents=document.getElementById("contents").value

   var cls=document.getElementById("cls")
   var textArea=document.getElementById("textArea")
   
   cls.value=oldCls
   textArea.innerHTML=contents
   initTalbe()
   //在编辑框内拖拉文件不触发上传初始化
   textAreaDragImgNoUpInit()
  return [oldCls,oldTitle,changFlag]
}


//修改地址栏中参数
function changeUrlParams(subEd)
{   
 var cls=getCls()
 var title=getTiltle()
 var url=new URL(window.location.href)
 if(cls!=false)
 {
  url.searchParams.set("cls",cls)
 }
 if(title!=false)
 {
  url.searchParams.set("title",title)
 }

 url.searchParams.set("subEd",subEd)
 window.history.pushState({},"",url)
}


//判断是否是手机
function isMobile() 
 {
   const regExp = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini|OpenHarmony/i;
   return  regExp.test(navigator.userAgent);
 }

 //登录
function pandLogin()
{
   var usr=getCookie("usr")
   var passWord=getCookie("passWord")
   if(usr!="th"||passWord!="w2009")
   {
      window.location.href="/"
      return "no"
   }
  else
  {
   return "yes"
  }
  
}


//获取cookie
function getCookie(keyIndex)
{
    

    if(document.cookie.length==0)
    {
        return "no"
    }
    else
    {
        var cookies=document.cookie.split(";")
    }
    
    for(var i=0;i<cookies.length;i++)
    {
        var sp=cookies[i].split("=")
        var key=sp[0].trim()
        var value=sp[1].trim()
        if(keyIndex==key)
        {
            return value
        }
    }
    return "no"
    
}

//颜色盘
function colorPlane()
{
   var fonteColorBox=document.getElementById("fonteColorBox")
   var backgroundColorBox=document.getElementById("backgroundColorBox")
   var w=document.getElementById("textArea").offsetWidth*0.8
   var color={"红色":"#FF0000","洋红色":"#FF00FF","粉红色":"#FFC0CB","紫色":"#800080",
              "绿色":"#00FF00", "草绿":"#76EE00","蓝色":"#0000FF","青色":"#00FFFF",
             "黄色":"#FFFF00","橙黄":"#FFA500","棕色":"#A52A2A",
              
              "黑色":"#000000","灰色":"#808080","深灰色":"#A9A9A9","浅灰色":"#D3D3D3",
              "白色":"#FFFFFF"
              }
   var string=""
   var hLength=Object.keys(color).length
   //一行放几个
   var L=4
   if(phone)
   {
      for(key in color)
      {
         var div=document.createElement("div")
         div.style.background=color[key]
         div.style.width=(w/L)+"px"
         div.style.height="100px"
         div.className=color[key]
         div.style.float="left"
         div.style.border="2px solid #ccc"
         div.setAttribute("onclick","filleValue()")
         string+=div.outerHTML

      }
      fonteColorBox.innerHTML+=string
      fonteColorBox.style.width=w+"px"
      fonteColorBox.style.height=hLength/L*100+80+"px"

      backgroundColorBox.innerHTML+=string
      // backgroundColorBox.style.display="block"
      backgroundColorBox.style.width=w+"px"
      backgroundColorBox.style.height=hLength/L*100+80+"px"

     var fontediv=fonteColorBox.getElementsByTagName("div")
     for(var i=0;i<fontediv.length;i++)
     {
        fontediv[i].setAttribute("onclick","filleValue(this,'getColor1','fonteColorBox')")
     }

     var fontediv=backgroundColorBox.getElementsByTagName("div")
     for(var i=0;i<fontediv.length;i++)
     {
        fontediv[i].setAttribute("onclick","filleValue(this,'getColor2','backgroundColorBox')")
     }
   }

   
}
//颜色填充函数，修改颜色容器值
function filleValue(th,ele,box)
   {
      var inp=document.getElementById(ele)
      var box=document.getElementById(box)
      inp.value=th.className
      inp.setAttribute("value",th.className)
      inp.value=th.className
      box.style.display="none"
      if(ele=="getColor1")
      {
         var showColor=document.getElementById("showColor1")
         showColor.style.backgroundColor=th.className
      }
      else
      {
         var showColor=document.getElementById("showColor2")
         showColor.style.backgroundColor=th.className
      }
      
   }
